package com.cyx.service.impl;

import com.cyx.exception.DeptHasEmpException;
import com.cyx.mapper.DeptMapper;
import com.cyx.mapper.EmpMapper;
import com.cyx.pojo.Dept;
import com.cyx.service.DeptService;
import com.cyx.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Override
    public List<Dept> findAll() {
        return deptMapper.findAll();
    }

    @Override
    public void deleteById(Integer id) {
        // 查询要删除的部门是否有学生
        if(empMapper.countByDeptId(id) > 0){
            throw new DeptHasEmpException("对不起，当前部门下有员工，不能直接删除");
        }
        deptMapper.deleteById(id);
    }

    @Override
    public void add(Dept dept) {
        // 更新时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }
    /**
     * 根据id查询部门
     *
     */
    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    public void update(Dept dept) {
        // 更新基础属性
        dept.setUpdateTime(LocalDateTime.now());
        // 调用Mapper接口方法更新数据
        deptMapper.update(dept);
    }
}
